package com.javaweb.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javaweb.admin.entity.*;
import com.javaweb.admin.entity.transmanage.*;
import com.javaweb.admin.mapper.*;
import com.javaweb.admin.query.*;
import com.javaweb.admin.service.ITransManageService;
import com.javaweb.common.common.BaseQuery;
import com.javaweb.common.utils.DateUtils;
import com.javaweb.common.utils.HttpUtils;
import com.javaweb.common.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class TransManageServiceImpl implements ITransManageService {

    @Autowired
    MDriverInfoMapper driverInfoMapper;
    @Autowired
    CustevaluateMapper custevaluateMapper;
    @Autowired
    MCarInfoMapper carInfoMapper;
    @Autowired
    D3endMessageLogMapper d3endMessageLogMapper;
    @Autowired
    D3endMessageLog2Mapper d3endMessageLog2Mapper;
    @Autowired
    NCCustAddrDocMapper ncCustAddrDocMapper;
    @Autowired
    MGpsDataMapper gpsDataMapper;
    @Autowired
    TempDataMapper tempDataMapper;
    @Autowired
    SmsevaluateMapper smsevaluateMapper;
    @Autowired
    TransRecordListMapper transRecordListMapper;
    @Autowired
    TransDetailMapper transDetailMapper;

    @Override
    public JsonResult getTransUserList(BaseQuery query) {
        TransUserQuery transUserQuery = (TransUserQuery) query;
        IPage<MDriverInfo> page = new Page<>(transUserQuery.getPage(), transUserQuery.getLimit());
        IPage<MDriverInfo> pageData = driverInfoMapper.getDriverInfoList(page, transUserQuery);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult saveTransUser(MDriverInfo entity) {
        try {
            UpdateWrapper<MDriverInfo> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("old", entity.getOld()).set("driverold", entity.getDriverold()).set("type", entity.getType())
                    .set("memo", entity.getMemo()).set("memo1", entity.getMemo1()).set("memo2", entity.getMemo2())
                    .set("memo3", entity.getMemo3()).eq("id", entity.getId());
            driverInfoMapper.update(new MDriverInfo(), updateWrapper);
            return JsonResult.success();
        } catch (Exception ex) {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    public JsonResult getCarInfoList(BaseQuery query) {
        MCarInfoQuery carInfoQuery = (MCarInfoQuery) query;
        IPage<MCarInfo> page = new Page<>(carInfoQuery.getPage(), carInfoQuery.getLimit());
        IPage<MCarInfo> pageData = carInfoMapper.getCarInfoList(page, carInfoQuery);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult saveCarInfo(MCarInfo entity) {
        try {
            UpdateWrapper<MCarInfo> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("hotdeviceid", entity.getHotdeviceid()).set("hotdeviceid2", entity.getHotdeviceid2()).set("type", entity.getType())
                    .set("gpsdeviceid", entity.getGpsdeviceid()).set("weight", entity.getWeight()).set("memo1", entity.getMemo1())
                    .set("memo2", entity.getMemo2()).eq("carid", entity.getCarid());
            carInfoMapper.update(new MCarInfo(), updateWrapper);
            return JsonResult.success();
        } catch (Exception ex) {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    public JsonResult getCustAddrList(BaseQuery query) {
        NCCustAddrDocQuery ncCustAddrDocQuery = (NCCustAddrDocQuery) query;
        IPage<NCCustAddrDoc> page = new Page<>(ncCustAddrDocQuery.getPage(), ncCustAddrDocQuery.getLimit());
        IPage<NCCustAddrDoc> pageData = ncCustAddrDocMapper.getCustAddrList(page, ncCustAddrDocQuery);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult getGpsDataList(BaseQuery query) {
        GpsDataQuery gpsDataQuery = (GpsDataQuery) query;
        IPage<GpsData> page = new Page<>(gpsDataQuery.getPage(), gpsDataQuery.getLimit());
        IPage<GpsData> pageData = gpsDataMapper.getGpsDataList(page, gpsDataQuery);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult getTempdataList(BaseQuery query) {
        TempdataQuery tempdataQuery = (TempdataQuery) query;
        IPage<TempData> page = new Page<>(tempdataQuery.getPage(), tempdataQuery.getLimit());
        IPage<TempData> pageData = tempDataMapper.getTempDataList(page, tempdataQuery);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult getRecordList(BaseQuery query) {
        TransRecordListQuery transRecordListQuery = (TransRecordListQuery) query;
        IPage<TransRecordList> page = new Page<>(transRecordListQuery.getPage(), transRecordListQuery.getLimit());
        IPage<TransRecordList> pageData = transRecordListMapper.getTransRecordList(page, transRecordListQuery);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult getDetail(BaseQuery query) {
        RecordListDetailQuery recordListDetailQuery = (RecordListDetailQuery) query;
        IPage<RecordListDetail> page = new Page<>(recordListDetailQuery.getPage(), recordListDetailQuery.getLimit());
        IPage<RecordListDetail> pageData = transRecordListMapper.getDetail(page, recordListDetailQuery);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult getTempdata1and2List(BaseQuery query) {
        RecordListTempdataQuery recordListTempdataQuery = (RecordListTempdataQuery) query;
        MCarInfoQuery carInfoQuery = new MCarInfoQuery();
        carInfoQuery.setCarcode(recordListTempdataQuery.getDevname());
        MCarInfo data = carInfoMapper.getHotdeviceid(carInfoQuery);

        recordListTempdataQuery.setHotdeviceid1(data.getHotdeviceid());
        recordListTempdataQuery.setHotdeviceid2(data.getHotdeviceid2());
        IPage<RecordListTempdata> page = new Page<>(recordListTempdataQuery.getPage(), recordListTempdataQuery.getLimit());
        IPage<RecordListTempdata> pageData = transRecordListMapper.getTempdata1and2List(page, recordListTempdataQuery);

        return JsonResult.success(pageData);
    }


    @Override
    public JsonResult saveCustAddr(NCCustAddrDoc entity) {
        try {
            UpdateWrapper<NCCustAddrDoc> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("lineaddr", entity.getLineaddr()).set("expectstart", entity.getExpectstart()).set("expectend", entity.getExpectend())
                    .set("notreceitime", entity.getNotreceitime()).set("linkuser", entity.getLinkuser()).set("linkphone", entity.getLinkphone())
                    .eq("pk_custaddr", entity.getPkCustaddr());
            ncCustAddrDocMapper.update(new NCCustAddrDoc(), updateWrapper);
            return JsonResult.success();
        } catch (Exception ex) {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    public JsonResult getTransCoordinates(BaseQuery query) {
        TransCoordinates transCoordinates = new TransCoordinates();
        //获取车牌号查询条件
        TransCoordinatesQuery coordinatesQuery = (TransCoordinatesQuery) query;
        String devname = ((TransCoordinatesQuery) query).getDevname();
        String[] devList = devname.split(",", -1);
        List<Features> featuresList = new ArrayList<>();
        for (String dev : devList) {
            coordinatesQuery.setDevname(dev);
            List<GpsData> gpsDataList = gpsDataMapper.getTransCoordinatesList(coordinatesQuery);
            Properties properties = new Properties();
            Geometry geometry = new Geometry();
            properties.setName(dev);

            Features features = new Features();
            features.setType("Feature");
            features.setProperties(properties);
            List<Point> coordinates = new ArrayList<>();
            for (GpsData data : gpsDataList) {
                Point point = new Point();
                point.add(data.getLng(), data.getLat());

                coordinates.add(point);
            }
            geometry.setType("LineString");
            geometry.setCoordinates(coordinates);
            features.setGeometry(geometry);
            featuresList.add(features);

        }
        transCoordinates.setFeatures(featuresList);
        transCoordinates.setType("FeatureCollection");
        return JsonResult.success(transCoordinates);

    }

    @Override
    public JsonResult getOrderForGoods(BaseQuery query) {
        OrderForGoodsQuery orderForGoodsQuery = (OrderForGoodsQuery) query;
        //IPage<OrderForGoods> page=new Page<>(recordListTempdataQuery.getPage(), recordListTempdataQuery.getLimit());
        List<OrderForGoods> pageData = gpsDataMapper.getOrderForGoods(orderForGoodsQuery);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult getSmsevaluate(BaseQuery query) {
        SmsevaluateQuery smsevaluateQuery = (SmsevaluateQuery) query;
        IPage<Smsevaluate> page = new Page<>(smsevaluateQuery.getPage(), smsevaluateQuery.getLimit());
        IPage<Smsevaluate> pageData = smsevaluateMapper.getSmsevaluate(page, smsevaluateQuery);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult getTransDetail(BaseQuery query) {
        TransDetailQuery transDetailQuery = (TransDetailQuery) query;
        IPage<TransDetail> page = new Page<>(transDetailQuery.getPage(), transDetailQuery.getLimit());
        IPage<TransDetail> pageData = transDetailMapper.getTransDetail(page, transDetailQuery);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult smsevaluateReissue(SmsevaluateReissueQuery query) {
        boolean rtn = false;
        for (Smsevaluate smsevaluate : query.getSmsevaluates()) {
            /*访问数据库获得SendGoodsTaskID,确定是否补发*/
            SmsevaluateStatus smsevaluateStatus = smsevaluateMapper.getStatus(smsevaluate);

            /*无数据需要补发*/
            if (smsevaluateStatus == null || smsevaluateStatus.getSendGoodsTaskID().isEmpty()) {
                List<CustVoicecode> custVoicecodes = smsevaluateMapper.getCustVoicecode(smsevaluate);
                for (CustVoicecode custVoicecode : custVoicecodes) {
                    if (custVoicecode.getStatus().equals("2")) {
                        break;
                    }
                    if (custVoicecode.getStatus().equals("4") && Integer.parseInt(custVoicecode.getNum()) > 0) {
                        rtn = true;
                    }
                    if (custVoicecode.getStatus().equals("5") && Integer.parseInt(custVoicecode.getNum()) > 0) {
                        rtn = true;
                    }
                    if (rtn) {
                        D3endMessageLog d3endMessageLog = new D3endMessageLog();
                        String un = "N5737774";
                        String pw = "we7da5QAZ0a3ec";
                        String phone = "";
                        String key = "";
                        String keys = "";
                        String jsonBodys = "";
                        String result = "";
                        String linkuser = "";
                        String article = "上海信谊天一药业有限公司物流服务评价平台。  尊敬的客户：盛邀大家对我司的物流服务和各项工作，给与评价，提出新建议，为药品物流提供更安全、更快捷的通道保障。" +
                                "上海信谊天一药业将继续宣示和践行“敬重生命、关爱健康”的企业理念。与您携手同行！";
                        String content = "【信谊天一药业】" + article + "请点击链接{http://dp.sinety.com:8091/?p={$var}}对我们的服务进行评价。您的评价和意见建议，就是提升我们工作效能的宝贵动力。";
                        PhoneAndUser phoneAndUser = smsevaluateMapper.getPhoneAndUser(smsevaluate);
                        phone = phoneAndUser.getLinkPhone();
                        linkuser = phoneAndUser.getLinkUser();
                        if (!phone.isEmpty()) {
                            d3endMessageLog.setLinkuser(linkuser);
                            d3endMessageLog.setLinkphone(phone);
                            d3endMessageLog.setTs(DateUtils.now());
                            d3endMessageLog.setAddrname(smsevaluate.getCustcodeSendAddr());
                            d3endMessageLog.setSendgoodstaskid(smsevaluate.getSendGoodsTaskID());
                            d3endMessageLog.setCustcode(smsevaluate.getCustcode());
                            d3endMessageLog.setMessage(content);
                            d3endMessageLog.setSentrult("已发送");
                             d3endMessageLogMapper.insert(d3endMessageLog);
                             key=d3endMessageLog.getId().toString();
                            byte[] bytes = key.getBytes();
                            BASE64Encoder encoder = new BASE64Encoder();
                            keys = encoder.encode(bytes);

                            int c = keys.length() - keys.indexOf("=");
                            keys = keys.replace("=", "") + "&a=" + c;
                            jsonBodys = "\"account\":\"" + un + "\",\"password\":\"" + pw + "\",\"params\":\"" + phone + "," + keys + "\",\"report\":\"true\",\"msg\":\"" + content + "\"";
                            HttpUtils.sendPost2("http://smssh1.253.com/msg/variable/json", "{"+jsonBodys+"}");
                            content = "【信谊天一药业】" +article+ "请点击链接{http://dp.sinety.com:8091/?p=" + keys + "}对我们的服务进行评价。您的评价和意见建议，就是提升我们工作效能的宝贵动力。";

                            smsevaluateMapper.updateMessageLog(content,key);


                        }

                    }


                }


            }
        }
        //增加短信日志


        return null;
    }

    @Override
    public JsonResult getCustevaluateList(BaseQuery query) {
        CustevaluateQuery custevaluateQuery = (CustevaluateQuery) query;
        custevaluateQuery.setMessagetime(custevaluateQuery.getDbilldate().substring(0,7));
        IPage<Custevaluate> page = new Page<>(custevaluateQuery.getPage(), custevaluateQuery.getLimit());
        IPage<Custevaluate> pageDate = custevaluateMapper.getCustevaluateList(page, custevaluateQuery);

        return JsonResult.success(pageDate);
    }

    @Override
    public JsonResult custevaluateReissue(CustevaluateReissueQuery query) {
        for (Custevaluate custevaluate : query.getCustevaluate()) {
            boolean rtn = true;
            if (rtn) {
                D3endMessageLog2 d3endMessageLog2=new D3endMessageLog2();
                String un = "N5737774";
                String pw = "we7da5QAZ0a3ec";
                String phone = custevaluate.getLinkPhone();
                String key="";
                String keys="";
                String jsonBodys="";
                String result = "";
                String article = "上海信谊天一药业有限公司物流服务评价平台。  尊敬的客户：盛邀大家对我司的物流服务和各项工作，给与评价，提出新建议，为药品物流提供更安全、更快捷的通道保障。" +
                        "上海信谊天一药业将继续宣示和践行“敬重生命、关爱健康”的企业理念。与您携手同行！";
                String content = "【信谊天一药业】" + article + "请点击链接{http://dp.sinety.com:8091/index.html?p={$var}}对我们的服务进行评价。您的评价和意见建议，就是提升我们工作效能的宝贵动力!";
                if (phone != "") {
                    d3endMessageLog2.setTs(DateUtils.now());
                    d3endMessageLog2.setCustcode(custevaluate.getCustcode());
                    d3endMessageLog2.setLinkPhone(phone);
                    d3endMessageLog2.setSentRult("已发送");
                    d3endMessageLog2.setMessage(content);
                    d3endMessageLog2.setMessagetime(DateUtils.now().toString().substring(0,7));
                    //d3endMessageLog2Mapper.insert(d3endMessageLog2);
                    //key=d3endMessageLog2.getId().toString();
                    byte[] bytes = key.getBytes();
                    BASE64Encoder encoder = new BASE64Encoder();
                    keys = encoder.encode(bytes);
                    int c = keys.length() - keys.indexOf("=");
                    keys = keys.replace("=", "") + "&a=" + c;
                    jsonBodys = "\"account\":\"" + un + "\",\"password\":\"" + pw + "\",\"params\":\"" + phone + "," + keys + "\",\"report\":\"true\",\"msg\":\"" + content + "\"";
                    //HttpUtils.sendPost2("http://smssh1.253.com/msg/variable/json", "{" + jsonBodys + "}");
                }

            }

        }
        return JsonResult.success();
    }
}
